package com.jerei.web.utils.ui;

import com.alibaba.fastjson.JSONObject;
import com.jerei.utils.UtilsCommon;
import freemarker.core.Environment;
import freemarker.template.*;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * Created by sunfeihu on 2016/11/15.
 */
public class DataGridTHTag implements TemplateDirectiveModel {

    private JSONObject defaultOptions = null;

    private void setDefault() {
        defaultOptions = new JSONObject();
        defaultOptions.put("sortable", true);
        defaultOptions.put("halign", "center");
        defaultOptions.put("align", "left");
        defaultOptions.put("width", 100);
    }

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        Writer out = env.getOut();
        this.setDefault();
        String dataOptions = UtilsCommon.getString(params.get("options"));
        dataOptions = dataOptions.replaceAll("\r\n", "");
        dataOptions = "{" + dataOptions + "}";
        JSONObject obj = JSONObject.parseObject(dataOptions);
        if (null != obj && obj.size() > 0) {
            for (String key : obj.keySet()) {
                defaultOptions.put(key, obj.get(key));
            }
        }
        if (null != defaultOptions && defaultOptions.size() > 0) {
            String str = "";
            for (String key : defaultOptions.keySet()) {
                if (defaultOptions.get(key) instanceof String) {
                    if (key.equals("formatter")) {
                        str += key + ":" + defaultOptions.get(key) + ",";
                    } else {
                        str += key + ":\"" + defaultOptions.get(key) + "\",";
                    }
                } else {
                    str += key + ":" + defaultOptions.get(key) + ",";
                }
            }
            str = str.substring(0, str.length() - 1);
            env.setLocalVariable("options", new SimpleScalar(str));
        }
        if (body != null) {
            body.render(env.getOut());
        } else {
            throw new RuntimeException("标签内部至少要加一个空格");
        }
    }
}
